using Microsoft.AspNetCore.Mvc;
using WorkflowCore.Interface;
using WorkflowApi.Models;
using WorkflowApi.Workflows;
using System.Text.Json;
using SqlSugar;

namespace WorkflowApi.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class WorkflowController : ControllerBase
    {
        private readonly IWorkflowHost _workflowHost;
        private readonly ILogger<WorkflowController> _logger;
        private readonly ISqlSugarClient _db;

        public WorkflowController(IWorkflowHost workflowHost, ILogger<WorkflowController> logger, ISqlSugarClient db)
        {
            _workflowHost = workflowHost;
            _logger = logger;
            _db = db;
            InitializeMockData();
        }

        #region 工作流定义管理

        [HttpPost("definitions")]
        public async Task<IActionResult> CreateWorkflowDefinition([FromBody] CreateWorkflowRequest request)
        {
            try
            {
                // 验证流程定义
                if (string.IsNullOrEmpty(request.Name))
                {
                    return BadRequest(new { success = false, message = "流程名称不能为空" });
                }

                if (!request.Steps.Any())
                {
                    return BadRequest(new { success = false, message = "流程步骤不能为空" });
                }

                var definition = new WorkflowDefinitionEntity
                {
                    Id = Guid.NewGuid().ToString(),
                    Name = request.Name,
                    Description = request.Description,
                    StepsJson = JsonSerializer.Serialize(request.Steps),
                    CreatedAt = DateTime.UtcNow,
                    IsActive = true
                };

                await _db.Insertable(definition).ExecuteCommandAsync();

                // 注册工作流定义到 Workflow-Core
                await RegisterWorkflowDefinition(request);

                return Ok(new { success = true, data = definition });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建工作流定义失败");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        [HttpGet("definitions")]
        public async Task<IActionResult> GetWorkflowDefinitions()
        {
            try
            {
                var list = await _db.Queryable<WorkflowDefinitionEntity>()
                    .OrderByDescending(x => x.CreatedAt)
                    .ToListAsync();
                return Ok(new { success = true, data = list });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工作流定义失败");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        [HttpGet("definitions/{id}")]
        public async Task<IActionResult> GetWorkflowDefinition(string id)
        {
            try
            {
                var definition = await _db.Queryable<WorkflowDefinitionEntity>().InSingleAsync(id);
                if (definition == null)
                    return NotFound(new { success = false, message = "工作流定义不存在" });
                return Ok(new { success = true, data = definition });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工作流定义失败");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        [HttpPut("definitions/{id}")]
        public async Task<IActionResult> UpdateWorkflowDefinition(string id, [FromBody] CreateWorkflowRequest request)
        {
            try
            {
                var definition = await _db.Queryable<WorkflowDefinitionEntity>().InSingleAsync(id);
                if (definition == null)
                    return NotFound(new { success = false, message = "工作流定义不存在" });

                definition.Name = request.Name;
                definition.Description = request.Description;
                definition.StepsJson = JsonSerializer.Serialize(request.Steps);

                await _db.Updateable(definition).ExecuteCommandAsync();

                return Ok(new { success = true, data = definition });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新工作流定义失败");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        [HttpDelete("definitions/{id}")]
        public async Task<IActionResult> DeleteWorkflowDefinition(string id)
        {
            try
            {
                var result = await _db.Deleteable<WorkflowDefinitionEntity>().Where(x => x.Id == id).ExecuteCommandAsync();
                if (result > 0)
                {
                    return Ok(new { success = true, message = "删除成功" });
                }
                return NotFound(new { success = false, message = "工作流定义不存在" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除工作流定义失败");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        #endregion

        #region 工作流实例管理

        [HttpPost("instances")]
        public async Task<IActionResult> StartWorkflow([FromBody] StartWorkflowRequest request)
        {
            try
            {
                var definition = await _db.Queryable<WorkflowDefinitionEntity>().InSingleAsync(request.DefinitionId);
                if (definition == null)
                    return BadRequest(new { success = false, message = "工作流定义不存在" });

                // 启动 Workflow-Core 工作流
                var workflowId = await _workflowHost.StartWorkflow("ApprovalWorkflow", new WorkflowData
                {
                    InstanceId = Guid.NewGuid().ToString(),
                    Properties = request.Data
                });

                var instance = new WorkflowInstanceEntity
                {
                    Id = workflowId,
                    DefinitionId = request.DefinitionId,
                    DataJson = JsonSerializer.Serialize(request.Data),
                    CreatedBy = "current-user",
                    Status = "Running",
                    CreatedAt = DateTime.UtcNow
                };

                await _db.Insertable(instance).ExecuteCommandAsync();

                // 创建第一个任务
                var steps = JsonSerializer.Deserialize<List<WorkflowStep>>(definition.StepsJson) ?? new();
                if (steps.Any())
                {
                    var firstStep = steps.OrderBy(s => s.Order).First();
                    foreach (var approver in firstStep.Approvers)
                    {
                        var task = new WorkflowTaskEntity
                        {
                            Id = Guid.NewGuid().ToString(),
                            InstanceId = workflowId,
                            StepId = firstStep.Id,
                            Assignee = approver,
                            Status = "Pending",
                            CreatedAt = DateTime.UtcNow
                        };
                        await _db.Insertable(task).ExecuteCommandAsync();
                    }
                }

                return Ok(new { success = true, data = instance });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "启动工作流失败");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        [HttpGet("instances")]
        public async Task<IActionResult> GetWorkflowInstances()
        {
            try
            {
                var list = await _db.Queryable<WorkflowInstanceEntity>()
                    .OrderByDescending(x => x.CreatedAt)
                    .ToListAsync();
                return Ok(new { success = true, data = list });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工作流实例失败");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        [HttpGet("instances/{id}")]
        public async Task<IActionResult> GetWorkflowInstance(string id)
        {
            try
            {
                var instance = await _db.Queryable<WorkflowInstanceEntity>().InSingleAsync(id);
                if (instance == null)
                    return NotFound(new { success = false, message = "工作流实例不存在" });
                return Ok(new { success = true, data = instance });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工作流实例失败");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        [HttpPost("instances/{id}/suspend")]
        public async Task<IActionResult> SuspendWorkflow(string id)
        {
            try
            {
                await _workflowHost.SuspendWorkflow(id);
                var instance = await _db.Queryable<WorkflowInstanceEntity>().InSingleAsync(id);
                if (instance != null)
                {
                    instance.Status = "Suspended";
                    await _db.Updateable(instance).ExecuteCommandAsync();
                }
                return Ok(new { success = true, message = "工作流已暂停" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "暂停工作流失败");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        [HttpPost("instances/{id}/resume")]
        public async Task<IActionResult> ResumeWorkflow(string id)
        {
            try
            {
                await _workflowHost.ResumeWorkflow(id);
                var instance = await _db.Queryable<WorkflowInstanceEntity>().InSingleAsync(id);
                if (instance != null)
                {
                    instance.Status = "Running";
                    await _db.Updateable(instance).ExecuteCommandAsync();
                }
                return Ok(new { success = true, message = "工作流已恢复" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "恢复工作流失败");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        #endregion

        #region 任务管理

        [HttpGet("tasks")]
        public async Task<IActionResult> GetTasks([FromQuery] string? assignee = null, [FromQuery] string? status = null)
        {
            try
            {
                var query = _db.Queryable<WorkflowTaskEntity>();
                if (!string.IsNullOrEmpty(assignee))
                    query = query.Where(t => t.Assignee == assignee);
                if (!string.IsNullOrEmpty(status))
                    query = query.Where(t => t.Status == status);

                var list = await query.OrderByDescending(x => x.CreatedAt).ToListAsync();
                return Ok(new { success = true, data = list });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取任务失败");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        [HttpPost("tasks/{taskId}/approve")]
        public async Task<IActionResult> ApproveTask(string taskId, [FromBody] ApproveTaskRequest request)
        {
            try
            {
                var task = await _db.Queryable<WorkflowTaskEntity>().InSingleAsync(taskId);
                if (task == null)
                    return NotFound(new { success = false, message = "任务不存在" });

                task.Status = request.Action;
                task.Comment = request.Comment;
                task.CompletedAt = DateTime.UtcNow;
                task.Action = request.Action;

                await _db.Updateable(task).ExecuteCommandAsync();

                // 处理委托
                if (request.Action == "Delegate" && !string.IsNullOrEmpty(request.DelegateTo))
                {
                    var newTask = new WorkflowTaskEntity
                    {
                        Id = Guid.NewGuid().ToString(),
                        InstanceId = task.InstanceId,
                        StepId = task.StepId,
                        Assignee = request.DelegateTo,
                        Status = "Pending",
                        CreatedAt = DateTime.UtcNow
                    };
                    await _db.Insertable(newTask).ExecuteCommandAsync();
                }

                // 处理加签
                if (request.Action == "AddSign" && request.AddSignUsers?.Any() == true)
                {
                    foreach (var userId in request.AddSignUsers)
                    {
                        var newTask = new WorkflowTaskEntity
                        {
                            Id = Guid.NewGuid().ToString(),
                            InstanceId = task.InstanceId,
                            StepId = task.StepId,
                            Assignee = userId,
                            Status = "Pending",
                            CreatedAt = DateTime.UtcNow
                        };
                        await _db.Insertable(newTask).ExecuteCommandAsync();
                    }
                }

                // 检查是否所有任务都已完成，如果是则进入下一步
                await CheckAndAdvanceWorkflow(task.InstanceId);

                return Ok(new { success = true, data = task });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "审批任务失败");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        #endregion

        #region 高级工作流步骤管理

        // 创建并行工作流步骤
        [HttpPost("steps/parallel")]
        public async Task<IActionResult> CreateParallelStep([FromBody] ParallelStepRequest request)
        {
            try
            {
                var step = new WorkflowStep
                {
                    Id = Guid.NewGuid().ToString(),
                    Name = request.Name,
                    Type = "parallel",
                    Order = request.Order,
                    Position = request.Position,
                    Properties = new Dictionary<string, object>
                    {
                        ["parallelRule"] = request.ParallelRule,
                        ["parallelBranches"] = request.ParallelBranches
                    }
                };

                return Ok(new { success = true, data = step, message = "并行步骤创建成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建并行步骤失败");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        // 创建脚本工作流步骤
        [HttpPost("steps/script")]
        public async Task<IActionResult> CreateScriptStep([FromBody] ScriptStepRequest request)
        {
            try
            {
                var step = new WorkflowStep
                {
                    Id = Guid.NewGuid().ToString(),
                    Name = request.Name,
                    Type = "script",
                    Order = request.Order,
                    Position = request.Position,
                    Properties = new Dictionary<string, object>
                    {
                        ["scriptType"] = request.ScriptType,
                        ["scriptContent"] = request.ScriptContent,
                        ["timeout"] = request.Timeout,
                        ["errorHandling"] = request.ErrorHandling
                    }
                };

                return Ok(new { success = true, data = step, message = "脚本步骤创建成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建脚本步骤失败");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        // 创建邮件工作流步骤
        [HttpPost("steps/email")]
        public async Task<IActionResult> CreateEmailStep([FromBody] EmailStepRequest request)
        {
            try
            {
                var step = new WorkflowStep
                {
                    Id = Guid.NewGuid().ToString(),
                    Name = request.Name,
                    Type = "email",
                    Order = request.Order,
                    Position = request.Position,
                    Properties = new Dictionary<string, object>
                    {
                        ["subject"] = request.Subject,
                        ["body"] = request.Body,
                        ["recipients"] = request.Recipients,
                        ["ccRecipients"] = request.CcRecipients
                    }
                };

                return Ok(new { success = true, data = step, message = "邮件步骤创建成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建邮件步骤失败");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        // 创建定时器工作流步骤
        [HttpPost("steps/timer")]
        public async Task<IActionResult> CreateTimerStep([FromBody] TimerStepRequest request)
        {
            try
            {
                var step = new WorkflowStep
                {
                    Id = Guid.NewGuid().ToString(),
                    Name = request.Name,
                    Type = "timer",
                    Order = request.Order,
                    Position = request.Position,
                    Properties = new Dictionary<string, object>
                    {
                        ["schedule"] = request.Schedule,
                        ["timerType"] = request.TimerType
                    }
                };

                return Ok(new { success = true, data = step, message = "定时器步骤创建成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建定时器步骤失败");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        // 创建等待工作流步骤
        [HttpPost("steps/wait")]
        public async Task<IActionResult> CreateWaitStep([FromBody] WaitStepRequest request)
        {
            try
            {
                var step = new WorkflowStep
                {
                    Id = Guid.NewGuid().ToString(),
                    Name = request.Name,
                    Type = "wait",
                    Order = request.Order,
                    Position = request.Position,
                    Properties = new Dictionary<string, object>
                    {
                        ["waitTime"] = request.WaitTime,
                        ["waitType"] = request.WaitType
                    }
                };

                return Ok(new { success = true, data = step, message = "等待步骤创建成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建等待步骤失败");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        #endregion

        #region 用户和组织管理

        [HttpGet("users")]
        public IActionResult GetUsers()
        {
            return Ok(new { success = true, data = _users });
        }

        [HttpGet("departments")]
        public IActionResult GetDepartments()
        {
            return Ok(new { success = true, data = _departments });
        }

        [HttpGet("roles")]
        public IActionResult GetRoles()
        {
            return Ok(new { success = true, data = _roles });
        }

        #endregion

        #region 私有方法

        private void InitializeMockData()
        {
            if (!_users.Any())
            {
                _users.AddRange(new[]
                {
                    new User { Id = "1", Name = "张三", Email = "zhangsan@company.com", DepartmentId = "1", Roles = new List<string> { "employee" } },
                    new User { Id = "2", Name = "李四", Email = "lisi@company.com", DepartmentId = "1", Roles = new List<string> { "manager" } },
                    new User { Id = "3", Name = "王五", Email = "wangwu@company.com", DepartmentId = "2", Roles = new List<string> { "employee" } },
                    new User { Id = "4", Name = "赵六", Email = "zhaoliu@company.com", DepartmentId = "2", Roles = new List<string> { "manager" } },
                    new User { Id = "5", Name = "总经理", Email = "ceo@company.com", DepartmentId = "3", Roles = new List<string> { "ceo" } }
                });
            }

            if (!_departments.Any())
            {
                _departments.AddRange(new[]
                {
                    new Department { Id = "1", Name = "技术部", ManagerId = "2" },
                    new Department { Id = "2", Name = "市场部", ManagerId = "4" },
                    new Department { Id = "3", Name = "总经办", ManagerId = "5" }
                });
            }

            if (!_roles.Any())
            {
                _roles.AddRange(new[]
                {
                    new Role { Id = "1", Name = "员工", Code = "employee" },
                    new Role { Id = "2", Name = "部门经理", Code = "manager" },
                    new Role { Id = "3", Name = "总经理", Code = "ceo" }
                });
            }
        }

        private async Task RegisterWorkflowDefinition(CreateWorkflowRequest request)
        {
            // 这里可以根据流程定义动态注册工作流
            // 目前使用固定的 ApprovalWorkflow
            if (!_workflowHost.Registry.IsRegistered("ApprovalWorkflow", 1))
            {
                _workflowHost.RegisterWorkflow<ApprovalWorkflow>();
            }
        }

        private async Task CheckAndAdvanceWorkflow(string instanceId)
        {
            var instance = await _db.Queryable<WorkflowInstanceEntity>().InSingleAsync(instanceId);
            if (instance == null) return;

            var definition = await _db.Queryable<WorkflowDefinitionEntity>().InSingleAsync(instance.DefinitionId);
            if (definition == null) return;

            var currentTasks = await _db.Queryable<WorkflowTaskEntity>()
                .Where(t => t.InstanceId == instanceId && t.Status == "Pending")
                .ToListAsync();

            if (currentTasks.Any()) return;

            var completedTasks = await _db.Queryable<WorkflowTaskEntity>()
                .Where(t => t.InstanceId == instanceId && t.Status == "Approved")
                .ToListAsync();

            var steps = JsonSerializer.Deserialize<List<WorkflowStep>>(definition.StepsJson) ?? new();
            var currentStepOrder = completedTasks.Max(t =>
            {
                var step = steps.FirstOrDefault(s => s.Id == t.StepId);
                return step?.Order ?? 0;
            });

            var nextStep = steps.FirstOrDefault(s => s.Order > currentStepOrder);
            if (nextStep != null)
            {
                foreach (var approver in nextStep.Approvers)
                {
                    var newTask = new WorkflowTaskEntity
                    {
                        Id = Guid.NewGuid().ToString(),
                        InstanceId = instanceId,
                        StepId = nextStep.Id,
                        Assignee = approver,
                        Status = "Pending",
                        CreatedAt = DateTime.UtcNow
                    };
                    await _db.Insertable(newTask).ExecuteCommandAsync();
                }
            }
            else
            {
                instance.Status = "Completed";
                instance.CompletedAt = DateTime.UtcNow;
                await _db.Updateable(instance).ExecuteCommandAsync();
            }
        }

        // 模拟数据存储（实际项目中应使用数据库）
        private static readonly List<WorkflowDefinition> _workflowDefinitions = new();
        private static readonly List<WorkflowInstance> _workflowInstances = new();
        private static readonly List<WorkflowTask> _workflowTasks = new();
        private static readonly List<User> _users = new();
        private static readonly List<Department> _departments = new();
        private static readonly List<Role> _roles = new();

        #endregion
    }
} 